/**
 * @page: 账期列表页面
 * @author: fj
 */
import { useEffect, useState, useMemo } from 'react';
import { message } from 'antd';
import HeaderTab from '@/components/CommonTab';
import Iconfont from '@/components/IconFont';
import PeriodTable from './PeriodTable';
import AdvanceModal from '../Modals/AdvanceModal';
import PayMent from '../Modals/PayMent';
import ZxinChainModal from '../Modals/ZxinChainModal';
import FormRender from '@/components/FormRender';
import OperaBtnRender from '@/components/OperaBtnRender';
import { useResize } from '@/hooks/useResize';
import { handleExportExcel2 } from '@/utils/utils.jsx';
import { tabArr, getFormItem } from './config.js';
import {
  queryAccountList,
  queryReturnAccountList,
  repaymentView,
  payCredit,
  createNewBill,
  creditdiscountApply,
  creditdiscountModify,
  creditdiscountRevoke,
} from '../../service';
import styles from './index.module.less';
import moment from 'moment';

const dateFormat = 'YYYY-MM-DD HH:mm:ss';

const periodList = ({ openDetailPage }) => {

  // 当前tab
  const [type, setType] = useState('1');
  //列表数据
  const [data, setData] = useState([]);
  // 搜索数据
  const [query, setQuery] = useState({
    timeType: '1'
  });
  //单行数据
  const [record, setRecord] = useState({});
  //账期预览数据
  const [paymentView, setPaymentView] = useState({});
  //还款弹窗
  const [payVisible, setPayVisible] = useState(false);
  //提前出账
  const [advanceVisible, setAdvanceVisible] = useState(false);
  //优惠状态筛选
  const [billState, setBillState] = useState(undefined);
  //申请/修改优惠账期
  const [ApplyBillConfig, setApplyBillConfig] = useState({
    visible: false,
    title: '申请优惠账期',
    type: 'add',
  });

  const [storeName, setStoreName] = useState("");

  const [visible, setVisible] = useState(false);//1:区块链保护说明弹窗
  //分页数据
  const [pages, setPages] = useState({
    current: 1,
    total: 0,
    pageSize: 10,
  });

  //点击供应商
  const changeStoreName = (val, index, obj) => {
    setStoreName(obj.storeName);
  } 

  //监听变更
  const { el: headerEl, height: headerHeight, onResize } = useResize();

  //表单数据
  const formArr = useMemo(() => {
    return getFormItem(storeName, changeStoreName, type);
  }, [storeName, changeStoreName, type])

  useEffect(() => {
    getAccountList(query, type, { ...pages, current: 1 });
    onResize();
  }, [type]);


  // 获取账期列表(历史和待还)
  const getAccountList = async (query, type, pages) => {
    START_LOADING();
    setData([]);
    let getList = queryAccountList;
    if (type == '2') {
      getList = queryReturnAccountList;
    }
    const { success, data = {} } = await getList({
      ...query,
      billingStatus: type == '1' ? '1,2' : type == '3' ? '3' : undefined, // 还款状态 1、未还款，2、已还款，3、未结清（部分还款）
      creditOrderState: type == '2' ? '1,2' : undefined, // 出账状态：1、待入账 2、已入账 3、已出账
      storeName: type == '2' ? undefined : storeName,
      storeId: type == '2' ? query.storeId: undefined,
      current: pages.current,
      size: pages.pageSize,
      startTime: query.payTime && type != 2
        ? moment(query.payTime[0]).format('YYYY-MM-DD HH:mm:ss')
        : undefined,
      endTime: query.payTime && type != 2
        ? moment(query.payTime[1]).format('YYYY-MM-DD HH:mm:ss')
        : undefined,
      payTime: undefined,
    });
    if (success) {
      const { records = [], total = 0 } = data;
      setData(records);
      setPages({
        ...pages,
        total,
      });
    }
    END_LOADING();
  };

  //账期还款预览
  const getRepaymentView = async (record) => {
    START_LOADING();
    setPaymentView({});
    setRecord(record);
    const { success, data = {} } = await repaymentView({
      accountNo: record.payAccountNo,
      merchantAccountNo: record.incomeAccountNo,
      period: record.period,
    });
    if (success) {
      setPayVisible(true);
      setPaymentView(data);
    }
    END_LOADING();
  };

  //账期还款提交
  const handleCredit = async (val) => {
    START_LOADING();
    const { success } = await payCredit({
      repaymentAmount: val.repaymentAmount,
      password: val.password,
      contractNo: record.contractNo,
      accountNo: record.payAccountNo,
      merchantAccountNo: record.incomeAccountNo,
      period: record.period,
      uuid: record.uuid,
      orderSrc: 7,
    });
    if (success) {
      message.success('提交成功');
      setPayVisible(false);
      getAccountList(query, type, {
        ...pages,
        current: 1,
      });
    }
    END_LOADING();
  };

  // 提前出账
  const handleAdvance = async () => {
    START_LOADING();
    const { success, data = {} } = await createNewBill({
      createSequenceType: 1,
      accountNo: record.payAccountNo,
      merchantNo: record.incomeAccountNo,
      contractNo: record.contractNo,
    });
    if (success) {
      if (data) {
        message.success('出账成功！');
        getAccountList({}, type, {
          ...pages,
          current: 1,
        });
      } else {
        message.error('出账失败！');
      }
    }
    setAdvanceVisible(false);
    END_LOADING();
  };

  // 申请优惠金额
  const applyDiscount = async (val, record) => {
    START_LOADING();
    const { success, data = {} } = await creditdiscountApply({
      contractNo: record.contractNo,
      period: record.period,
      remark: val.remark,
      discountAmount: val.discountAmount,
    });
    if (success) {
      message.success('申请成功！');
      getAccountList({}, type, {
        ...pages,
        current: 1,
      });
    } else {
      message.error('申请失败！');
    }
    setApplyBillConfig({
      visible: false,
    });
    END_LOADING();
  };

  // 修改优惠金额
  const modifyDiscount = async (val, record) => {
    START_LOADING();
    const { success, data = {} } = await creditdiscountModify({
      id: record.disId,
      remark: val.remark,
      discountAmount: val.discountAmount,
    });
    if (success) {
      message.success('修改成功！');
      getAccountList({}, type, {
        ...pages,
        current: 1,
      });
    } else {
      message.error('修改失败！');
    }
    setApplyBillConfig({
      visible: false,
    });
    END_LOADING();
  };

  // 撤销优惠金额
  const revokeDiscount = async (record) => {
    START_LOADING();
    const { success, data = {} } = await creditdiscountRevoke({
      id: record.disId,
    });
    if (success) {
      message.success('撤销成功！');
      getAccountList({}, type, {
        ...pages,
        current: 1,
      });
    } else {
      message.error('撤销失败！');
    }
    END_LOADING();
  };

  // tab组件数据
  const HeaderTabProps = {
    type,
    data: tabArr,
    //tab改变
    onChange(val) {
      setType(val);
    },
  };

  // 列表组件数据
  const PeriodListProps = {
    type,
    data,
    pages,
    ApplyBillConfig,
    openDetailPage,
    headerHeight,
    changePages(current, pageSize) {
      setPages({
        ...pages,
        current,
        pageSize,
      });
      getAccountList(query, type, { ...pages, current, pageSize });
    },
    getRepayment(record) {
      getRepaymentView(record);
    },
    getAdvance(record) {
      setRecord(record);
      setAdvanceVisible(true);
    },
    billState,
    handleFilter(val) {
      //点击选中筛选条件
      setBillState(val);
      setQuery({
        disState: val,
      });
    },
    //点击筛选的确定或重置
    handleOkFilter(count, val) {
      if (count == 1) {
        //重置
        setBillState(val);
        getAccountList({ ...query, disState: undefined }, type, {
          ...pages,
        });
      } else {
        getAccountList(
          {
            ...query,
            disState: billState
              ? billState.length == 4
                ? undefined
                : billState.join(',')
              : undefined,
          },
          type,
          {
            ...pages,
          }
        );
      }
    },
    //点击申请/优惠账期优惠
    handleSetApplyBillConfig(visible, title, type) {
      setApplyBillConfig({
        visible: visible,
        title: title,
        type: type,
      });
    },
    //点击申请/修改优惠账期
    handleApplyDiscount(type, val, record) {
      if (type == 'add') {
        //申请
        applyDiscount(val, record);
      } else {
        //修改
        modifyDiscount(val, record);
      }
    },
    //撤销优惠账期
    handleRevokeDiscount(record) {
      revokeDiscount(record);
    },
  };

  // 搜索组件数据
  const PeriodSearchProps = {
    type,
    query,
    // 点击搜索事件
    handleSearch(val) {
      setQuery({
        ...val,
        startTime: val.payTime
          ? moment(val.payTime[0]).format(dateFormat)
          : undefined,
        endTime: val.payTime
          ? moment(val.payTime[1]).format(dateFormat)
          : undefined,
      });
      setData([]);
      setPages({ ...pages, current: 1 });
      getAccountList(
        {
          ...val,
          disState: billState
            ? billState.length == 4
              ? undefined
              : billState.join(',')
            : undefined,
        },
        type,
        { ...pages, current: 1 }
      );
    },
    // 重置
    handleReset() {
      setData([]);
      setQuery({});
      setPages({ ...pages, current: 1 });
      getAccountList(
        {
          disState: billState
            ? billState.length == 4
              ? undefined
              : billState.join(',')
            : undefined,
        },
        type,
        {
          ...pages,
          current: 1,
        }
      );
    },
  };

  // 分页组件数据
  const PageProps = {
    pages,
    handleChange(current, pageSize) {
      setPages({
        ...pages,
        current,
        pageSize,
      });
      getAccountList(query, type, { ...pages, current, pageSize });
    },
  };

  //账期还款弹窗数据
  const payProps = {
    payVisible,
    paymentView,
    handleCancel() {
      setPayVisible(false);
    },
    handleOk(val) {
      handleCredit(val);
    },
  };

  //提前出账Pops
  const advanceProps = {
    advanceVisible,
    handleCancel() {
      setAdvanceVisible(false);
    },
    handleOk() {
      handleAdvance();
    },
  };

  //表格导出
  const exportExcel = () => {
    if (data.length) {
      if (data.length > 10000) {
        message.info('导出数据超出1万条，请重新选择时间范围');
      } else {
        START_LOADING();
        const params = {
          ...query,
          billingStatus: type == '1' ? '1,2' : type == '3' ? '3' : undefined, // 还款状态 1、未还款，2、已还款，3、未结清（部分还款）
          creditOrderState: type == '2' ? '1,2' : undefined, // 出账状态：1、待入账 2、已入账 3、已出账
          startTime: query.startTime ? query.startTime : undefined,
          endTime: query.endTime ? query.endTime : undefined,
          payTime: undefined,
        };
        let url = `/blade-user/ReceptionCredit/waitPayBillExcelStore`,
          title = '待还账期.xlsx';
        if (type == '2') {
          (url = `/blade-user/ReceptionCredit/billsReceivablesExcel`),
            (title = '未出账期.xlsx');
        } else if (type == '3') {
          (url = `/blade-user/ReceptionCredit/hisBillExcel`),
            (title = '历史账期.xlsx');
        }
        handleExportExcel2(url, params, title, () => {
          END_LOADING();
        });
      }
    } else {
      message.info('暂无可导出的数据');
    }
  };

  const ZxinChainModalProps = {
    visible,
    handleCancel() {
      setVisible(false);
    }
  }

  //表单渲染组件
  const FormRenderProps = {
    query,
    formArr,
    formConfig: {
      name: 'child-account-manage-form',
      style: { marginBottom: '16px' }
    },
    clickSearch(val) {
      setQuery({
        ...val,
        startTime: val.payTime
          ? moment(val.payTime[0]).format(dateFormat)
          : undefined,
        endTime: val.payTime
          ? moment(val.payTime[1]).format(dateFormat)
          : undefined,
      });
      setData([]);
      setPages({ ...pages, current: 1 });
      getAccountList(
        {
          ...val,
          disState: billState
            ? billState.length == 4
              ? undefined
              : billState.join(',')
            : undefined,
        },
        type,
        { ...pages, current: 1 }
      );
    },
    clickReset() {
      setData([]);
      setQuery({ timeType: '1'});
      setPages({ ...pages, current: 1 });
      setStoreName("");
      getAccountList(
        {
          disState: billState
            ? billState.length == 4
              ? undefined
              : billState.join(',')
            : undefined,
        },
        type,
        {
          ...pages,
          current: 1,
        }
      );
    },
  }

  //操作按钮
  const btnArr = [
    { elType: 'button', text: '表格导出', onClick: exportExcel }
  ]

  return (
    <>
      <HeaderTab {...HeaderTabProps} />
      <div ref={headerEl}>
        <div className={styles.headerTitle}>
          <div>1、已出账的待还账期，如果发生单据金额变更或退款，会生成新的未出账期</div>
          <div>2、账期金额是正数，代表用户需要还款，如果是负数，代表是商户需要退还用户的钱</div>
          <div>3、直发订单、普通订单，出账后会拆成两个“待还账期”</div>
        </div>
        <FormRender {...FormRenderProps} />
      </div>
      <div className='global-page-wrap'>
        <div style={{ display: 'flex', alignItems: 'baseline' }}>
          <OperaBtnRender style={{ marginBottom: '12px' }} btnArr={btnArr} />
          {type == 3 && (
            <div style={{ flex: 1, textAlign: 'right'}}>
            <Iconfont type="iconqukuailianAPP" style={{ fontSize: '22px' }} />
            <span style={{ color: '#1DC11D', verticalAlign: 'top' }}>区块链保护中 </span>
            <span onClick={() => setVisible(1)} style={{ marginLeft: '4px' }}>
              <Iconfont type="iconxinxishuoming" style={{ fontSize: '20px', cursor: 'pointer' }} />
              </span>
          </div>)}
          {type == '1' ? (
            <div className="other-product-item">
              <div style={{ marginBottom: '10px' }}>
                <span>已逾期：</span>
                {(data || []).map((item) => (
                  <span key={item.id} style={{ color: 'red' }}>
                    {item.duePastDayNum > 0 ? (
                      <span>
                        {item.storeName}（{item.duePastDayNum}天）
                      </span>
                    ) : (
                      ''
                    )}
                  </span>
                ))}
              </div>
            </div>
          ) : (
            ''
          )}
        </div>
        <PeriodTable {...PeriodListProps} />
      </div>
      <PayMent {...payProps} />
      <AdvanceModal {...advanceProps} />
      <ZxinChainModal {...ZxinChainModalProps} />
    </>
  );
};

export default periodList;
